package com.jiawa.train.business.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jiawa.train.business.domain.Req.TrainQueryReq;
import com.jiawa.train.business.domain.Req.TrainSaveReq;
import com.jiawa.train.business.domain.Train;
import com.jiawa.train.business.domain.TrainExample;
import com.jiawa.train.business.domain.resp.TrainQueryResp;
import com.jiawa.train.business.mapper.TrainMapper;
import com.jiawa.train.common.resp.PageResp;
import com.jiawa.train.common.util.SnowUtil;
import jakarta.validation.Valid;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class TrainService {
    @Autowired
    private TrainMapper trainMapper;

    public PageResp<TrainQueryResp> queryList(TrainQueryReq req) {
        TrainExample example = new TrainExample();

        PageHelper.startPage(req.getPage(),req.getSize());

        List<Train> trainList = trainMapper.selectByExample(example);
        PageInfo<Train> pageInfo = new PageInfo<>(trainList);
        List<TrainQueryResp> respList = BeanUtil.copyToList(trainList, TrainQueryResp.class);
        PageResp<TrainQueryResp> pageResp = new PageResp<>();

        pageResp.setTotal(pageInfo.getTotal());
        pageResp.setList(respList);
        return pageResp;
    }

    public void save(TrainSaveReq req) {

        Train train = new Train();
        BeanUtils.copyProperties(req, train);

        if(ObjectUtil.isNull(train.getId())){
          train.setId(SnowUtil.getSnowflakeNextId());
          train.setCreateTime(new Date());
          train.setUpdateTime(new Date());
          trainMapper.insert(train);
        }else {
            train.setUpdateTime(new Date());
            trainMapper.updateByPrimaryKeySelective(train);
        }
    }

    public void delete(Long id) {
        trainMapper.deleteByPrimaryKey(id);
    }

    public List<TrainQueryResp> queryAll() {
        TrainExample example = new TrainExample();
        List<Train> trainList = trainMapper.selectByExample(example);
        return BeanUtil.copyToList(trainList, TrainQueryResp.class);
    }
}
